package com.hanm.util;

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SSHExecuter {

	public static String execute(String command, String host, int port, String user, String passwd) {
		String osName = System.getProperty("os.name");
		// ps -ef|grep tomcat|grep -v grep|awk '{print $2}'
		StringBuffer sb = new StringBuffer();
		try {
			JSch jsch = new JSch();
			if (osName.toUpperCase().indexOf("WINDOWS") > -1) {
				jsch.setKnownHosts("c:\\known_hosts");
			} else {
				jsch.setKnownHosts("$HOME/.ssh/known_hosts");
			}
			Session session = jsch.getSession(user, host, port);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.setPassword(passwd);
			session.connect();
			Channel channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(command);
			InputStream in = channel.getInputStream();
			channel.connect();
			int nextChar;
			while (true) {
				while ((nextChar = in.read()) != -1) {
					sb.append((char) nextChar);
				}
				if (channel.isClosed()) {
					System.out.println("exit-status: " + channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}
			channel.disconnect();
			session.disconnect();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return sb.toString();
	}
}